
const adminDao = require('../sql/adminDao')
const jwt = require('jsonwebtoken')
const config = require('../config')
const bcryptjs = require('bcryptjs')
const ip = require('../utils/ipUtils')
const path = require('path')
const fs = require('fs')
const mysql = require('../db/mysql')
// 验证码插件
const svgCaptcha = require('svg-captcha')


const url = ip.base + '/admin/avatar/';

// 验证码
exports.security = (req,res)=>{
    try {
        // 生成验证码图片
        let code = svgCaptcha.create(config.securityCodeConfig);
        let info = {
            id: Math.floor(Math.random()*10000) + Date.now(),
            code: code.text.toLowerCase()
        }
        const key = jwt.sign(info, config.securityKey, {expiresIn : config.securityExpiresIn})
        res.success({
            svgImg: code.data,
            uuid: key
        })
    }catch (e) {
        console.log(e)
        res.status(500).fail('服务器错误')
    }
}

// 登录
exports.login = (req,res)=>{
    try{
        // 校验验证码
        jwt.verify(req.body.uuid, config.securityKey, async (err, date)=>{
            if(err) {
                if(err.message==='jwt expired') return res.fail("验证码已过期，请重新获取验证码")
                else return res.fail("数据不合法！")
            }
            if(req.body.code.toLowerCase()!==date.code) return res.fail("验证码错误");
            let row = await mysql(adminDao.selectAdminByUserName, [req.body.username])
            // 解析密码。判断是否一致
            if(row.length===1&&bcryptjs.compareSync(req.body.password, row[0].password)){
                const user = {
                    id: row[0].id,
                    username: row[0].username,
                    type: row[0].type,
                }
                const tokenString = jwt.sign(user, config.jwtSecretKey, { expiresIn: config.expiresIn });
                return res.success({
                    token: "Bearer " + tokenString,
                    userInfo:{
                        username: row[0].username,
                        nickname: row[0].nickname,
                        tel: row[0].tel,
                        avatar: url + row[0].avatar
                    }
                }, "登录成功")
            }
            else return res.fail("账号名或者密码错误", 401);
        })
    }catch (e) {
        console.log(e)
        res.status(500).fail('服务器错误')
    }

}

// 修改头像
exports.updateAvatar = (req,res)=>{
    try {
        const file = req.file;
        // 获取文件的后缀名
        const endName = path.extname(file.originalname);
        // 拼接新的文件名称
        let fileName =  file.filename + endName;
        let newFileName = path.join(__dirname, '../file/avatar/') + fileName;
        // 将旧的文件名称改成新名称
        fs.rename(file.path, newFileName, async (err)=>{
            if(err) return res.status(500).fail("服务器错误", 500);
            let avatar = await mysql(adminDao.selectAvatarByID, [req.user.id])
            let row = await mysql(adminDao.updateAvatar, [fileName, req.user.id])
            if(avatar.length==1){
                try {
                    // 删除本地文件
                    fs.unlinkSync(path.join(__dirname, '../file/avatar/') + avatar[0].avatar);
                }catch (e) {
                    console.log(e)
                }
            }
            if(row.affectedRows==1) return res.success({}, '修改成功')
            else return res.fail('修改失败')
        })
    }catch (e) {
        console.log(e)
        res.status(500).fail('服务器错误')
    }
}

// 获取头像
exports.getFile = (req,res)=>{
    try {
        let options = {
            root: path.join(__dirname, '../file/avatar/')
        };
        let fileName = req.params.name;
        res.sendFile(fileName, options);
    }catch (e) {
        console.log(e)
        res.status(500).fail('服务器错误')
    }
}

// 获取用户信息
exports.info = async (req,res)=>{
    try {
        let row = await mysql(adminDao.selectUserById, [req.user.id]);
        res.success({
            userInfo:{
                username: row[0].username,
                nickname: row[0].nickname,
                tel: row[0].tel,
                avatar: ip.base + '/admin/avatar/' + row[0].avatar
            }
        });
    }catch (e) {
        console.log(e)
        res.status(500).fail('服务器错误')
    }
}

// 更新密码
exports.updatePWD = async (req,res)=>{
    try {
        const row = await mysql(adminDao.selectUserById, [req.user.id])
        // 解析密码。判断是否一致
        if(row.length===1&&bcryptjs.compareSync(req.body.oldPassword, row[0].password)){
            const password = bcryptjs.hashSync(req.body.newPassword, 10)
            const row1 = await mysql(adminDao.updatePWD, [password, req.user.id]);
            if(row1.affectedRows==1) return res.success({}, '修改成功');
            else return res.fail('修改失败')
        }
        else return res.fail("原密码错误", 401);
    }catch (e) {
        console.log(e)
        res.status(500).fail('服务器错误')
    }
}



